// 导入数据库操作模块
const { get } = require('http')
const db = require('../../db/index')
// 导入邮件处理模块
const { sentEmail } = require('../../utils/email.js')
// 导入utils
const { getCurrentTime, getRandom16DigitNumber, calculationTime } = require('../../utils/user.js')
const { encryption, decrypt } = require('../../utils/password.js')
// 引入token的秘钥
var { TOKEN_KEY, TIME } = require('../../store/index')
const jwt = require('jsonwebtoken')

// 获取所有用户信息
exports.getAllUserInfo = (req, res) => {
    // 1 代表未删除  0代表删除
    const sql = `select * from user_detail where u_state=1 and ua_id=10001`
    db.query(sql, (err, results) => {
        if (err) return res.operationFailed(err)
        let userInfo = [ ...results ]
        for (const key in userInfo) {
            delete userInfo[key].password
            delete userInfo[key].u_state
            delete userInfo[key].security_question
        }
        res.operationSuccess('success', '', '获取用户信息成功！', userInfo)
    })
}

// 用户使用自定义账号注册
exports.registrationByUserId = (req, res) => {
    let { userId, password } = req.body
    if(userId == undefined || userId == '' || password == undefined || password == '') {
        return res.operationSuccess('failure', 'ERR003', '账号或密码不能为空！', [])
    }
    const selectSql = `select * from user_detail where user_id='${ userId }'`
    db.query(selectSql, (selectErr, selectRes) => {
        if(selectErr) return res.operationFailed(selectErr)
        if(selectRes.length != 0) return res.operationSuccess('failure', 'ERR001', '该账号已存在！', [])
        const random16DigitNumber = getRandom16DigitNumber()
        const uid = `uid_${ random16DigitNumber }`
        let encryptedPwd = encryption(password) // 加密后的密码
        const sql = `insert into user_detail(uid, user_id, password, u_state, ua_id, avator, nickname, signature, sex, area) value('${uid}', '${userId}', '${encryptedPwd}', 1, 10001, '/api/out/serverImage/avator/default_avator.jpg', '${uid}', '未知', '未知', '未知')`
        db.query(sql, (err, results) => {
            if(err) return res.operationFailed(err)
            return res.operationSuccess('success', '', '注册成功！', results)
        })
    })
}

// 用户使用邮箱登录
exports.loginByEmail = (req, res) => {
    console.log('/out/user/loginByEmail ')
    let { u_email } = req.body
    if(u_email == undefined || u_email == '') {
        return res.operationSuccess('failure', 'ERR005', '邮箱不能为空！', [])
    }
    const selectSql = `select * from user_detail where u_email='${ u_email }' and ua_id=10001`
    db.query(selectSql, (selectErr, selectRes) => {
        if(selectErr) return res.operationFailed(selectErr)
        if(selectRes.length == 0) {
            // 用户未使用过该邮箱登录或未使用该邮箱绑定其他账号
            return res.operationSuccess('failure', 'ERR008', '用户未使用过该邮箱登录或未使用该邮箱绑定其他账号！', [])
        } else {
            // 用户使用过该邮箱登录或使用过该邮箱绑定其他账号，直接登录
            let user = { ...selectRes[0], password: '', security_question: '' }
            let token = jwt.sign(user, TOKEN_KEY, { expiresIn: TIME })
            return res.send({
                code: 200,
                message: '操作成功！',
                data: { status: 'success', message: '使用邮箱登录成功！', token: token, results: { ...selectRes[0], password: '', token: token } },
            })
            // return res.operationSuccess('success', '', '使用邮箱登录成功！', results)
        }
    })
}

// 用户使用邮箱注册
exports.registrationByEmail = (req, res) => {
    let { u_email } = req.body
    const  random16DigitNumber = getRandom16DigitNumber()
    const uid = `uid_${ random16DigitNumber }`
    const sql = `insert into user_detail(uid, u_email, user_id, nickname, avator, signature, sex, area, u_state, ua_id) value('${uid}', '${u_email}', '${u_email}', '${uid}', '/api/out/serverImage/avator/default_avator.jpg', '', '未知', '未知', 1, 10001)`
    console.log('registrationByEmail', sql)
    db.query(sql, (err, results) => {
        if(err) return res.operationFailed(err)
        const selectSql = `select * from user_detail where u_email='${ u_email }' and ua_id=10001`
        db.query(selectSql, (err1, results1) => {
            if(err1) return res.operationFailed(err1)
            if(results1.length == 0 || (results1[0].password && results1[0].password != '' && password !== decrypt(results1[0].password))) {
                return res.operationSuccess('failure', 'ERR002', '账号或密码错误，请重新输入！', [])
            }
            let user = { ...results1[0], password: '', security_question: '' }
            let token = jwt.sign(user, TOKEN_KEY, { expiresIn: TIME })
            return res.send({
                code: 200,
                message: '操作成功！',
                data: { status: 'success', message: '登录成功', token: token, results: { ...results1[0], password: '', token: token } },
            })
        })
        // return res.operationSuccess('success', '', '使用邮箱注册成功！', [])
    })
}

// 用户绑定邮箱
exports.bindEmail = (req, res) => {
    let { u_email } = req.body
    let { uid } = req.auth
    const selectSql = `select * from user_detail where u_email='${u_email}'`
    db.query(selectSql, (err1, results1) => {
        if(err1) return res.operationSuccess('failure', 'ERR015', '绑定邮箱失败！', err1)
        if(results1.length == 0) {
            const sql = `update user_detail set u_email='${u_email}' where uid='${uid}'`
            db.query(sql, (err2, results2) => {
                if(err2) return res.operationSuccess('failure', 'ERR015', '绑定邮箱失败！', err2)
                return res.operationSuccess('success', '', '绑定邮箱成功！', [])
            })
        } else {
            return res.operationSuccess('failure', 'ERR016', '该邮箱已绑定其他账号！', [])
        }
    })
}

// 用户获取邮箱验证码
exports.getVerificationCodeByEmail = (req, res) => {
    // method 用于辨别用户获取该验证码是用于登录还是忘记密码，如果是登录就不需要判断用户是否使用过该邮箱进入此系统
    let { userType, u_email, method } = req.body
    // userType == 'A' ? dataBaseTableName = 'admin' : dataBaseTableName = 'user_detail'
    // let email = userType == 'A' ? 'a_email' : 'u_email'
    let type = userType == 'A' ? '10002' : '10001'
    const selectSql = `select * from user_detail where u_email='${ u_email }' and ua_id=${type}`
    new Promise((resolve, rejected) => {
        if(method != 'login') {
            db.query(selectSql, (err, selectResults) => {
                if(err) return res.operationFailed(err)
                if(selectResults.length == 0) return res.operationSuccess('failure', 'ERR007', '该邮箱不存在，请重新输入！', [])
                resolve(selectResults)
            })
        } else {
            resolve('')
        }
    }).then((selectResults) => {
        // 发送邮箱验证码
        sentEmail(u_email).then((sentEmailResult) => {
            if (sentEmailResult.err) {
                return res.operationSuccess('failure', 'ERR006', '邮箱发送验证码失败，请重试！', sentEmailResult.err)
            }
            let sentTime = getCurrentTime('dateTime')
            let verificationCode = sentEmailResult.verificationCode
            const addVerificationCodeSql = `insert into email(u_email, sent_time, verification_code, e_state) values('${ u_email }', '${ sentTime }', '${ verificationCode }', 1)`
            db.query(addVerificationCodeSql, (err, results) => {
                if (err) return res.operationFailed(err)
                return res.operationSuccess('success', '', '邮箱发送成功！', [])
            })
        })
    })
}

// 判断验证码是否失效
exports.verificationCodeExpire = (req, res) => {
    let { u_email, verification_code } = req.body
    const sql = `select * from email where u_email='${ u_email }' and verification_code='${ verification_code }' and e_state=1`
    db.query(sql, (err, results) => {
        if (err) return res.operationFailed(err)
        if(results.length != 0) {
            let timeDiff = calculationTime(results[0].sent_time)
            let verificationCodeId = results[0].eid
            // const deleteVerificationCodeSql = `delete from email where eid=${ verificationCodeId }`
            const deleteVerificationCodeSql = `update email set e_state=0 where eid=${ verificationCodeId }`
            db.query(deleteVerificationCodeSql, (deletErr, deletRes) => {
                if (deletErr) return res.operationFailed(deletErr)
                if(timeDiff > 5) return res.operationSuccess('failure', 'ERR004', '邮箱验证码不存在或已失效，请重新获取验证码！', [])
                else {
                    return res.operationSuccess('success', '', '邮箱验证码正确！', { email: u_email})
                }
            })
            // if(timeDiff > 5) {
            // } else {
            //     const deleteVerificationCodeSql = `delete from email where eid=${ verificationCodeId }`
            //     db.query(deleteVerificationCodeSql, (deletErr, deletRes) => {
            //         if (deletErr) return res.operationFailed(deletErr)
            //         // return res.operationSuccess('failure', 'ERR004', '邮箱验证码不存在或已失效，请重新获取验证码！', [])
            //         return res.operationSuccess('success', '', '邮箱验证码正确！', { email: u_email})
            //     })
            // }
        } else {
            return res.operationSuccess('failure', 'ERR004', '邮箱验证码不存在或已失效，请重新获取验证码！', [])
        }
    })
}

// 用户使用账号登录
exports.loginByUserId = (req, res) => {
    // 如果不传入userType, 默认是用户登录
    let { userType, userId, password } = req.body
    // 记录查询的是用户的id还是管理员的id    A 是管理员   U是普通用户
    let ua_id = 0
    userType != 'A' ? ua_id = 10001 : ua_id = 10002
    const selectSql = `select * from user_detail where user_id='${ userId }' and ua_id=${ua_id}`
    db.query(selectSql, (err, results) => {
        if(err) return res.operationFailed(err)
        if(results.length == 0 || (results[0].password && results[0].password != '' && password !== decrypt(results[0].password))) {
            return res.operationSuccess('failure', 'ERR002', '账号或密码错误，请重新输入！', [])
        }
        let user = { ...results[0], password: '', security_question: '' }
        let token = jwt.sign(user, TOKEN_KEY, { expiresIn: TIME })
        return res.send({
            code: 200,
            message: '操作成功！',
            data: { status: 'success', message: '登录成功', token: token, results: { ...results[0], password: '', token: token } },
        })
    })
}

// 用户登出系统
exports.userLoginOut = (req, res) => {
    const token = req.headers.authorization.split(' ')[1];
    console.log('token', token)
    jwt.verify(token, 'secretKey', (err, decoded) => {
        console.log('decoded', decoded)
        console.log('err', err)
        if (err) {
            console.log('Token验证失败')
            return res.status(401).json({ message: 'Token验证失败' });
        } else {
            // 根据用户信息更新数据库中的 token
            // 或者将该 token 标记为无效
            console.log('登出成功')
            return res.status(200).json({ message: '登出成功' });
        }
    })
}

// 使用邮箱重置密码
exports.resetPassword = (req, res) => {
    const { userType, email, newPassword } = req.body
    const sql1 = `select * from user_detail where u_email=${email} and ua_id=${userType} and u_state=1`
    // console.log('sql1', sql1)
    db.query(sql1, (err1, result1) => {
        // console.log('err1', err1)
        if(err1) return res.operationSuccess('failure', 'ERR008', '用户已注销账号或未使用该邮箱登录过本软件！', [])
        if(result1.length == 0) return res.operationSuccess('failure', 'ERR008', '用户未使用过该邮箱登录或未使用该邮箱绑定其他账号！', [])
        let encryptedPwd = encryption(newPassword) 
        const sql2 = `update user_detail set password='${ encryptedPwd }' where u_email=${email} and ua_id=${userType}`
        // console.log(sql2)
        db.query(sql2, (err2, result2) => {
            // console.log('err2', err2)
            if(err2) return res.operationSuccess('failure', 'ERR011', '重置密码失败！', [])
            return res.operationSuccess('success', '', '重置密码成功！', [])
        })
    })
}

// 根据uid删除用户（将用户状态更新为 0）
exports.deleteUserById = (req, res) => {
    let { uid } = req.body
    const sql = `update user_detail set u_state=0 where uid in (${ uid })` 
    db.query(sql, (err, results) => {
        if(err) return res.operationSuccess('failure', 'ERR013', '删除用户失败！', err)
        return res.operationSuccess('success', '', '删除用户成功！', [])
    })
}

// 根据uid/账号查找用户信息（模糊查询）
exports.findUserByUidOrUserId = (req, res) => {
    let { searchType, searchText } = req.body
    let type = searchType == 'uid' ? 'uid' : 'user_id'
    const selectSql = `select * from user_detail where ${ type } like '%${ searchText }%' and u_state=1` 
    db.query(selectSql, (err, results) => {
        if(err) return res.operationSuccess('failure', 'ERR012', '查找用户失败！', err)
        let userInfo = [ ...results ]
        for (const key in userInfo) {
            delete userInfo[key].password
            delete userInfo[key].u_state
            delete userInfo[key].security_question
        }
        return res.operationSuccess('success', '', '查找用户成功！', userInfo)
    })
}

// 获取用户信息
exports.getUserInfoAndDetail = (req, res) => {
    const { uid } = req.auth
    // 查询用户信息
    const sql1 = `select * from user_detail where uid='${ uid }'`
    // 查询用户收藏的诗歌
    const sql2 = `select * from user_poetry up, poetry2 p where up.uid='${ uid }' and up.pid=p.pid and up.bp_collection=1`
    // 查询用户收藏的诗单
    const sql3 = `select * from poem_list_collect plc, poems_list pl where plc.uid='${ uid }' and pl.pl_id=plc.pl_id and plc.is_collect=1 and plc_state=1 and pl_state=1`
    // 查询用户创建的诗单
    const sql4 = `select * from poems_list where uid='${ uid }' and pl_state=1`
    // 查询用户创建的各诗单下古诗
    const sql5 = `select * from poems_list pl, poems_list_poetry plp where pl.uid='${ uid }' and pl.pl_state=1 and pl.pl_id=plp.pl_id and plp.plp_state=1`
    // console.log(sql2)
    db.query(`${sql1};${sql2};${sql3};${sql4};${sql5}`, (err, results) => {
        if(err) return res.operationSuccess('failure', 'ERR014', '获取个人信息失败！', err)
        let userInfo = { ...results[0] }
        for (const key in userInfo) {
            delete userInfo[key].password
            delete userInfo[key].u_state
            delete userInfo[key].security_question
        }
        let a = results[4]
        console.log(a)
        let obj = {
            userInfo: userInfo[0],
            collectPoetry: results[1],
            collectPoems: results[2],
            createPoems: results[3],
        }
        // console.log(results)
        return res.operationSuccess('success', '', '获取个人信息成功！', obj)
    })
}

// 获取用户信息
exports.getUserInfo = (req, res) => {
    const { uid } = req.auth
    const selectSql = `select * from user_detail where uid='${ uid }'`
    db.query(selectSql, (err, results) => {
        if(err) return res.operationFailed(err)
        let user = { ...results[0], password: '', security_question: '' }
        return res.operationSuccess('success', '', '获取个人信息成功！', user)
    })
}

// 根据id更新用户信息
exports.updateUserById = (req, res) => {
    const file = req.file
    const { nickname, signature, sex, birthday, area } = req.query
    const { uid } = req.auth
    let sql = ''
    if(file) {
        sql = `update user_detail set avator='/api/out/serverImage/avator/${file.filename}' where uid='${uid}'`
    } else {
        sql = `update user_detail set nickname='${nickname}', signature='${signature}', sex='${sex}', birthday='${birthday}', area='${area}' where uid='${uid}'`
    }
    db.query(sql, (err, result) => {
        if(err) return res.operationSuccess('failure', 'ERR098', '编辑诗单失败！', err)
        const selectSql = `select * from user_detail where uid='${ uid }'`
        db.query(selectSql, (err2, results2) => {
            if(err2) return res.operationFailed(err2)
            let user = { ...results2[0], password: '', security_question: '' }
            return res.operationSuccess('success', '', '获取个人信息成功！', user)
        })
        // return res.operationSuccess('success', '', '编辑诗单成功！', [])
    })
}

// 用户绑定邮箱
exports.userBindingEmail = (req, res) => {
    
}